package org.setamv.springcloud.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;

@RestController
@RequestMapping("/greetings")
public class GreetingController {

    private static final Logger LOGGER = LoggerFactory.getLogger(GreetingController.class);

    @Value("${spring.application.id}")
    private String applicationId;

    @RequestMapping(value = "/from/{yourName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String sayHello(@PathVariable String yourName, HttpServletRequest request) throws Exception {
        URI uri = new URI(request.getRequestURL().toString());
        String requestSource = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort();
        String greetings = "Hi, " + yourName + "! Welcome to [" + applicationId + "]. request from " + requestSource;
        return greetings;
    }

    /**
     * 睡眠10秒后返回，用于测试延迟的熔断，例如hystrix
     */
    @RequestMapping(value = "/from/{yourName}/slowly", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String sayHelloSlowly(@PathVariable String yourName, HttpServletRequest request) throws Exception {
        Thread.sleep(10 * 1000);
        URI uri = new URI(request.getRequestURL().toString());
        String host = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort();
        String greetings = "Hi, " + yourName + "! Welcome to " + host + ".";
        return greetings;
    }
}
